package com.twu.biblioteca.movie;

import com.twu.biblioteca.item.ItemDAO;
import com.twu.biblioteca.item.Items;
import com.twu.biblioteca.movie.Movie;
import com.twu.biblioteca.utils.MyFileReader;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Enrico on 16/09/2014.
 */
public class MovieDAOFileImpl implements ItemDAO {

    @Override
    public Items<Movie> getItems() {
        return read();
    }

    public Items<Movie> read() {
        List<String> itemList = MyFileReader.read("movieList.csv");
        Iterator<String> iter = itemList.iterator();

        List<Movie> movieList = new ArrayList<Movie>();

        while (iter.hasNext()) {
            String[] fields = fields(iter.next());

            String name = fields[0];
            int year = Integer.parseInt(fields[1]);
            String director = fields[2];
            double rating = Double.parseDouble(fields[3]);

            movieList.add(new Movie(name, year, director, rating));
        }

        return new Items<Movie>(movieList);
    }

    public String[] fields(String line) {
        return line.split(",");
    }
}
